import { login } from '@/api/login'
import {
  getUserInfo,
  setUserInfo,
  removeUserInfo
} from '@/utils/auth'

const user = {
  state: {
    userInfo: getUserInfo()
  },

  mutations: {
    SET_USERINFO: (state, data) => {
      state.userInfo = data
      setUserInfo(JSON.stringify(data))
    },
    REMOVE_USERINFO: (state) => {
      state.userInfo = null
      removeUserInfo()
    }
  },

  actions: {
    // 登录
    LOGIN({ commit }, params) {
      return new Promise((resolve, reject) => {
        login(params).then(response => {
          commit('SET_USERINFO', response.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LOGINOUT({ commit }) {
      return new Promise(resolve => {
        commit('REMOVE_USERINFO')
        resolve()
      })
    }
  }
}

export default user
